#include "taskstorybyversion.h"
#include "ui_taskstorybyversion.h"
#include "mainwindow.h"
#include <QMessageBox>
#include <QDesktopServices>

class MyDateTimeScaleFormatter1 : public KDGantt::DateTimeScaleFormatter
{
public:
    MyDateTimeScaleFormatter1() : DateTimeScaleFormatter(Month, "MM"){}

//    /*reimp*/QDateTime nextRangeBegin(const QDateTime& datetime) const
//    {
//        return currentRangeBegin(datetime).addMonths(1);
//    }
//    /*reimp*/QDateTime currentRangeBegin(const QDateTime& datetime) const
//    {
//        return datetime;
//    }

    /*reimp*/QString text(const QDateTime& dt) const
    {
        return QObject::tr("%1年%2月").arg(dt.date().year()).arg(dt.date().month());
    }
};

class MyStandardItem : public QStandardItem
{
public:
    MyStandardItem(const QVariant &v)
        : QStandardItem()
    {
        setData(v, Qt::DisplayRole);
        // setFlags( flags() & ~Qt::ItemIsEditable );
    }
    MyStandardItem(const QString &v)
        : QStandardItem()
    {
        setData(v, Qt::DisplayRole);
        // setFlags( flags() & ~Qt::ItemIsEditable );
    }
    MyStandardItem(const QDate &dt, int role,int rolo1)
        : QStandardItem()
    {
        setData(QVariant::fromValue(dt), role);
        setData(QVariant::fromValue(dt), rolo1);
    }
};

TaskStoryByVersion::TaskStoryByVersion(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TaskStoryByVersion)
{
    ui->setupUi(this);

    this->setLayout(ui->gridLayout);

    //MainWindow *mw = static_cast<MainWindow *>(parent);
    m_mwindow = static_cast<MainWindow *>(QWidget::parentWidget());
    m_mwindow->initComboBoxData(ui->cb_projectName,"产品名称","");
 //   mw->initComboBoxData(ui->cb_versionName,"迭代版本号",ui->cb_projectName->currentText());

    ui->de_startDate->setReadOnly(true);
    ui->de_endDate->setReadOnly(true);

    mlayout  = new QVBoxLayout();
    mlayout->addWidget(&view);
    ui->wd_taskStoryVer->setLayout(mlayout);

    view.splitter()->setStretchFactor(0, 1);
    view.splitter()->setStretchFactor(1, 3);

    //设置甘特图的表头

    KDGantt::DateTimeScaleFormatter *upperFormatter,*lowerFormatter;

    grid.setUserDefinedUpperScale(new MyDateTimeScaleFormatter1());

    lowerFormatter = new KDGantt::DateTimeScaleFormatter(KDGantt::DateTimeScaleFormatter::Day,
                                                         QString::fromLatin1("dd"),
                                                         QString::fromLatin1("%1"),
                                                         Qt::AlignHCenter);
    grid.setUserDefinedLowerScale(lowerFormatter);
    grid.setScale(KDGantt::DateTimeGrid::ScaleUserDefined);
    grid.setDayWidth(38.);//设置甘特图的每天的宽度

    //grid.setStartDateTime(QDateTime::currentDateTime().addDays(-30));
    // grid.setNoInformationBrush( Qt::NoBrush );
    view.setGrid(&grid);
    view.setModel(&model);

    QStringList headlist;
    headlist <<"需求任务名称"<<"类型"<<"预计日期"<<"截止日期"<<"完成日期"<<"状态"<<"研发人员"<<"累计耗时"<<"ID";
    model.setHorizontalHeaderLabels(headlist);

    auto *leftView = qobject_cast<QTreeView *>(view.leftView());
    Q_ASSERT(leftView);
    leftView->header()->setStyleSheet("QHeaderView::section {background-color:#1E90FF;}");
    leftView->setColumnHidden(1, true);
    leftView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    leftView->header()->setStretchLastSection(true);
    leftView->setColumnWidth(0,500);
    leftView->setColumnWidth(2,90);
    leftView->setColumnWidth(3,90);
    leftView->setColumnWidth(4,90);
    leftView->setColumnWidth(5,60);
    leftView->setColumnWidth(6,60);
    leftView->setColumnWidth(7,60);
    leftView->setColumnWidth(8,0);
 //   leftView->setAlternatingRowColors(true);
    leftView->setStyleSheet("QTreeView::item{height:30px;alternate-background-color:rgb(135,206,235);}");

    connect(view.leftView(), SIGNAL(doubleClicked(const QModelIndex &)), this,SLOT(slotRowDoubleClicked(const QModelIndex &)));

}



TaskStoryByVersion::~TaskStoryByVersion()
{
    delete ui;
}

void TaskStoryByVersion::slotRowDoubleClicked(const QModelIndex index)
{
    QString taskId, taskUrl;
    QAbstractItemModel *model = view.model();
    if (model && index.isValid()) {
        //        // 获取整行数据，这里假设你有5列数据
        //        for (int i = 0; i < model->columnCount(); ++i) {
        //            QVariant data = model->data(index.sibling(index.row(), i));
        //            // 打印或处理数据
        //            qDebug() << "Column" << i << ": " << data.toString();
        QVariant data = model->data(index.sibling(index.row(), 8));
        if (data.isValid()) {
            taskId = data.toString();
            taskUrl = "http://pms.kpy.cloud/index.php?m=task&f=view&taskID=" + taskId;
            QDesktopServices::openUrl(QUrl(taskUrl));
        }
    } else {
        qDebug() << "Invalid index clicked";
    }

//    QString text = index.data(Qt::DisplayRole).toString();
//    qDebug()<<text;

}

void TaskStoryByVersion::on_cb_projectName_currentTextChanged(const QString &arg1)
{
    qDebug()<<"cb_projectName_currentTextChanged"<<arg1;

    m_prjVerPlan.clear();
    //MainWindow *mw = static_cast<MainWindow *>(QWidget::parentWidget());
    m_prjVerPlan = m_mwindow ->dbMySql->getProjectVerPlan(arg1);
    int num = m_prjVerPlan.size();
    //qDebug() << "m_prjVerPlan is:" << num;
    QStringList sList;
    for(int i=0;i<num;i++)
    {
        sList<<m_prjVerPlan[i].verPlanName;
       // qDebug()<< m_prjVerPlan[i].verPlanName<<m_prjVerPlan[i].verPlanId;
    }
    ui->cb_versionName->clear();
    ui->cb_versionName->addItems(sList);
}


void TaskStoryByVersion::on_cb_versionName_currentTextChanged(const QString &arg1)
{
    int num = m_prjVerPlan.size();
    for(int i=0;i<num;i++)
    {
        if(m_prjVerPlan[i].verPlanName ==arg1)
        {
            ui->de_startDate->setDate(QDate::fromString(m_prjVerPlan[i].verStartDate,"yyyy-MM-dd"));
            ui->de_endDate->setDate(QDate::fromString(m_prjVerPlan[i].verEndDate,"yyyy-MM-dd"));
            break;
        }
    }
}


void TaskStoryByVersion::on_bt_query_clicked()
{
    QString verPlanName = ui->cb_versionName->currentText();
    if(verPlanName.length()==0)
    {
        QMessageBox::StandardButton result = QMessageBox::information(this, "提示","该项目没有版本计划");
        return;
    }
    QString verPlanId,sVerDate,eVerDate;
    //int num = m_prjVerPlan.size();
    //qDebug()<<num<<verPlanName;
    for(int i=0;i<m_prjVerPlan.size();i++)
    {
        if(m_prjVerPlan[i].verPlanName ==verPlanName)
        {
            verPlanId = m_prjVerPlan[i].verPlanId;
            sVerDate = m_prjVerPlan[i].verStartDate;
            eVerDate = m_prjVerPlan[i].verEndDate;
            break;
        }
    }
    //MainWindow *mw = static_cast<MainWindow *>(QWidget::parentWidget());
    QList<StoryTaskByVer> recList = m_mwindow ->dbMySql->getStoryTaskByVerPlan(verPlanId);

    model.removeRows(0, model.rowCount());
    QBrush brush(QColor(135,206,235));

    int verNum = recList.size();
    QStandardItem *storyItem;
    //qDebug() << "start:" << QDateTime::currentDateTime() << verPlanId << verNum;
    for (int i = 0; i < verNum; i++)
    {
        if (i == 0)//第1条记录
        {
            storyItem = new MyStandardItem(recList.at(i).storyName);
            storyItem->setData(brush, Qt::BackgroundRole);
            if (recList.at(i).taskName.length())//该需求有任务
            {
                storyItem->appendRow(QList<QStandardItem *>()
                                     << new MyStandardItem(recList.at(i).taskName)
                                     << new MyStandardItem(KDGantt::TypeTask)
                                     << new MyStandardItem(recList.at(i).taskStartDate,Qt::DisplayRole,KDGantt::StartTimeRole)
                                     << new MyStandardItem(recList.at(i).taskEndDate,Qt::DisplayRole,KDGantt::EndTimeRole)
                                     << new MyStandardItem(recList.at(i).taskFinishDate)
                                     << new MyStandardItem(recList.at(i).taskStatus)
                                     << new MyStandardItem(recList.at(i).taskUser)
                                     << new MyStandardItem(recList.at(i).taskConsumed)
                                    << new MyStandardItem(recList.at(i).taskId));
               // qDebug()<<recList.at(i).taskUser;
            }
            model.appendRow(QList<QStandardItem *>()
                            << storyItem << new MyStandardItem(KDGantt::TypeMulti /*Summary*/)
                            << new MyStandardItem(QString()) << new MyStandardItem(QString())
                            << new MyStandardItem(QString()));//将第一个需求和它的任务添加到模型中
        }
        else
        {
            if (recList.at(i).storyName != recList.at(i - 1).storyName)//如果第i条记录和前面i-1条记录是不相同需求，则新加需求信息到模型中
            {
                storyItem = new MyStandardItem(recList.at(i).storyName);
                storyItem->setData(brush, Qt::BackgroundRole);
            }
            if (recList.at(i).taskName.length())
            {
                storyItem->appendRow(QList<QStandardItem *>()
                                     << new MyStandardItem(recList.at(i).taskName)
                                     << new MyStandardItem(KDGantt::TypeTask)
                                     << new MyStandardItem(recList.at(i).taskStartDate,Qt::DisplayRole,KDGantt::StartTimeRole)
                                     << new MyStandardItem(recList.at(i).taskEndDate,Qt::DisplayRole,KDGantt::EndTimeRole)
                                     << new MyStandardItem(recList.at(i).taskFinishDate)
                                     << new MyStandardItem(recList.at(i).taskStatus)
                                     << new MyStandardItem(recList.at(i).taskUser)
                                     << new MyStandardItem(recList.at(i).taskConsumed)
                                    << new MyStandardItem(recList.at(i).taskId));
               // qDebug()<<recList.at(i).taskUser;
            }
            if (recList.at(i).storyName != recList.at(i - 1).storyName)
            {
                model.appendRow(
                    QList<QStandardItem *>()
                    << storyItem << new MyStandardItem(KDGantt::TypeMulti /*Summary*/)
                    << new MyStandardItem(QString()) << new MyStandardItem(QString())
                    << new MyStandardItem(QString()));
            }
        }
    }
    auto *leftView = qobject_cast<QTreeView *>(view.leftView());
    leftView->expandAll();
    grid.setStartDateTime(QDateTime::fromString(sVerDate, "yyyy-MM-dd"));
    //qDebug() << "end:" << QDateTime::currentDateTime();
}

